package com.wangfei.lecture.httpclient4_5;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangfei.lecture.SM.SMUtil;
import okhttp3.*;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class UploadTest {
    public static Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){
        Logger log = LoggerFactory.getLogger(UploadTest.class);

        Map<String,Object> resultMap = new HashMap<String,Object>();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try{
            //把一个普通参数和文件上传给下面这个地址    是一个servlet
            HttpPost httpPost = new HttpPost(postUrl);
            //把文件转换成流对象FileBody
            FileBody fundFileBin = new FileBody(postFile);
            //设置传输参数
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            multipartEntity.addPart("datFile", fundFileBin);//相当于<input type="file" name="media"/>

            //设计文件以外的参数
            Set<String> keySet = postParam.keySet();
            for (String key : keySet) {
                //相当于<input type="text" name="name" value=name>
                multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("application/octet-stream", Consts.UTF_8)));
            }

            HttpEntity reqEntity =  multipartEntity.build();
            httpPost.setEntity(reqEntity);

            log.info("发起请求的页面地址 " + httpPost.getRequestLine());
            //发起请求   并返回请求的响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                log.info("----------------------------------------");
                //打印响应状态
                //log.info(response.getStatusLine());
                resultMap.put("statusCode", response.getStatusLine().getStatusCode());
                //获取响应对象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //打印响应长度
                    log.info("Response content length: " + resEntity.getContentLength());
                    //打印响应内容
                    resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
                }
                //销毁
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally{
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("uploadFileByHTTP result:"+resultMap);
        return resultMap;
    }
    public static void uploadOkHttp(String url) throws Exception{
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("datFile","/Users/wangfei/Downloads/SPF41030020221111.dat",
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                new File("/Users/wangfei/Downloads/SPF41030020221111.dat")))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
        Response response = client.newCall(request).execute();
        String resData = response.body().string();
        System.out.println("okHttp: " + resData);
        System.out.println(SMUtil.sm4Decrypt("pGmo2jZkrR8JqlQn", Hex.decode(resData)));
    }
    //测试
    public static void main(String args[]) throws Exception {
        //要上传的文件的路径
//        String filePath = "/Users/wangfei/Downloads/SPF41030020221111.dat";
//        String postUrl  = "http://123.7.180.231:8084/SPFBankInterfaceTest/SpecialChannel/DayEndReconciliation?param=";
//        Map<String,String> postParam = new HashMap<String,String>();
//        File postFile = new File(filePath);
//        Map<String,Object> resultMap = uploadFileByHTTP(postFile,postUrl,postParam);
//        System.out.println(resultMap);
//        uploadOkHttp();
    }
    @Test
    public void getToken() throws Exception {
        String sm4Key = "pGmo2jZkrR8JqlQn";
        String getTokenData = "{\"typeId\":\"8000\",\"bankOrgId\":\"20123\",\"loginName\":\"cszy01\",\"password\":\"#123#45\",\"submitDataTime\":\"2022-11-11 11:51:22\",\"other\":\"\"}";
        String getTokenUrl = "http://123.7.180.231:8084/SPFBankInterfaceTest/FundAccount/AccountAuth?param=";
        byte[] enBytes = SMUtil.sm4Encrypt(sm4Key, getTokenData);
        String enStr = Hex.toHexString(enBytes);
        getTokenUrl = getTokenUrl + enStr;
        System.out.println(getTokenUrl);
        String token = TestHttp.test(getTokenUrl);
        token = SMUtil.sm4Decrypt(sm4Key, Hex.decode(token));
        System.out.println(token);
        JSONObject jsonObject = JSON.parseObject(token);
        String tokenValue = jsonObject.getString("token");
        String uploadUrl = "http://123.7.180.231:8084/SPFBankInterfaceTest/FundAccount/AccountAuth?param=";
        String sendData = "{\"token\":\"MDJiZDhjN2FmM2VjNDc0YmEwMmVhMzE5OWRiMDJlN2E=\",\"typeId\":\"8920\",\"bankOrgId\":\"20123\",\"submitDataTime\":\"2022-11-11 16:36:22\",\"districtId\":\"410300\"}";
        JSONObject jsonObject1SendData = JSON.parseObject(sendData);
        jsonObject1SendData.put("token", tokenValue);
        sendData = JSON.toJSONString(jsonObject1SendData);
        enBytes = SMUtil.sm4Encrypt(sm4Key, sendData);
        sendData = Hex.toHexString(enBytes);
        uploadOkHttp(uploadUrl+sendData);
    }
}